package TableAdditions;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

import Utility.DatePicker;
import Tables.VehicleTableInterface;

public class VehicleAddition extends JFrame {
	
	
    private JTextField licencePlateField;
    private JTextField kmField;
    private JTextField lastMaintenanceField;
    private JTextField insurenceEndDateField;
    private JTextField nextInspectionField;
    private JComboBox driverIdField;
    int[] personelId;
    int driverId2;
    
    
	public String km;
	public String driverId="";
	public String licencePlate;
	public String insurenceEndDate;
	public String lastMaintenance;
	public String nextInspection;
	public int vehicleAvailability=1;
	private String selectedDriverName;
	
    private JButton vehicleAddButton;
    VehicleTableInterface cti;
    
    public VehicleAddition(final VehicleTableInterface cti) {
		super("Araç Ekleme Ekranı");
		this.cti = cti;
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setSize(600,200);
		getContentPane().setLayout(null);
		
		JLabel codeLabel = new JLabel("Plaka");
		codeLabel.setBounds(20, 10, 90, 20);
		getContentPane().add(codeLabel);
		
		licencePlateField = new JTextField();
		licencePlateField.setBounds(157, 11, 130, 20);
		getContentPane().add(licencePlateField);
		licencePlateField.setColumns(10);
		
		JLabel authorityLabel = new JLabel("Şoför İsmi");
		authorityLabel.setBounds(20, 40, 90, 20);
		getContentPane().add(authorityLabel);
		
		driverIdField = new JComboBox();
		driverIdField.setBounds(157, 40, 130, 20);
		getContentPane().add(driverIdField);//kmField
		//driverIdField.setColumns(10);
		
		   try {
			    Connection conn = null;
		        Statement stmt = null;
		        ResultSet rss = null;

		        String url = "jdbc:mysql://localhost:3306/mydb";
		        String user = "root";
		        String password = "qweasdzxc";
		        
		        conn = (Connection) DriverManager.getConnection(url, user, password);
				stmt = (Statement) conn.createStatement();
				
				driverIdField.addItem("Personel Adı");
				//TG updated to get data from view : view_personel_ordered_by_name
				//rss=stmt.executeQuery("SELECT * from personel WHERE activity='1'");
				rss = stmt.executeQuery("Select * from view_personel_ordered_by_name");
				
				int counter=0;
				while(rss.next()){
					counter++;					
				}
				
				if(counter>0){
					rss.first();
					personelId= new int[counter];
					int m=0;
					if(rss.getInt("personel_vehicle_id")==-1){
							driverIdField.addItem(rss.getString("personel_name"));
							personelId[m]=rss.getInt("personel_id");
							m++;
					}
			
					while(rss.next()){
						if(rss.getInt("personel_vehicle_id")==-1){
							personelId[m]=rss.getInt("personel_id");
							driverIdField.addItem(rss.getString("personel_name"));
							m++;
						}
					}
				}
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		   driverIdField.addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent event) {
					// TODO Auto-generated method stub
					

                  JComboBox comboBox = (JComboBox) event.getSource();
   
                  //
                  // Print the selected items and the action command.
                  //
                  Object selected = comboBox.getSelectedItem();
                  selectedDriverName=selected.toString();
                 
                  String command = event.getActionCommand();
                 
                  
                  int index= comboBox.getSelectedIndex();
                  if(index==0){
                	  driverId2=-1;
                  }
                  else{
                	  driverId2=index; 
                  }
                  
                  if(selected.toString().equals("Personel Adı")){
                	  vehicleAvailability=1;
                  }
                  else{
                	  vehicleAvailability=0;
                  }
                
                  // '"+cidField.getText()+"'
                  
                  //
                  // Detect whether the action command is "comboBoxEdited"
                  // or "comboBoxChanged"
                  //
                  if ("comboBoxEdited".equals(command)) {
                      //System.out.println("User has typed a string in " +
                        //      "the combo box.");
                  } else if ("comboBoxChanged".equals(command)) {
                      //System.out.println("User has selected an item " +
                        //      "from the combo box.");
                  }
                  
                  
               
				
				
              
					
				}
      		
      	});
		
		
		
		
	
		
		JLabel PhoneLabel = new JLabel("Kilometre");
		PhoneLabel.setBounds(305, 40, 90, 20);
		getContentPane().add(PhoneLabel);
		
		JButton lastMAintanenceDateButton = new JButton("Son Bakım");
		lastMAintanenceDateButton.setBounds(305, 10, 110, 20);
		lastMAintanenceDateButton.addActionListener(new ActionListener() {
	        public void actionPerformed(ActionEvent ae) {
	            lastMaintenanceField.setText(new DatePicker(VehicleAddition.this).setPickedDate());
	        }
	    });
		getContentPane().add(lastMAintanenceDateButton);
		
		lastMaintenanceField = new JTextField();
		lastMaintenanceField.setBounds(442, 11, 130, 20);
		getContentPane().add(lastMaintenanceField);
		lastMaintenanceField.setColumns(10);
		
		kmField = new JTextField();
		kmField.setBounds(442, 41, 130, 20);
		getContentPane().add(kmField);
		kmField.setColumns(10);
		
		JButton address1Label = new JButton("Muayene");
		address1Label.setBounds(20, 70, 125, 20);
		address1Label.addActionListener(new ActionListener() {
	        public void actionPerformed(ActionEvent ae) {
	            	nextInspectionField.setText(new DatePicker(VehicleAddition.this).setPickedDate());
	        }
	    });
		getContentPane().add(address1Label);
		
		nextInspectionField = new JTextField();
		nextInspectionField.setBounds(157, 72, 130, 20);
		getContentPane().add(nextInspectionField);
		nextInspectionField.setColumns(10);
		
		JButton adress2Label = new JButton("Sigorta Bitim");
		adress2Label.setBounds(305, 69, 125, 20);
		adress2Label.addActionListener(new ActionListener() {
	        public void actionPerformed(ActionEvent ae) {
	            insurenceEndDateField.setText(new DatePicker(VehicleAddition.this).setPickedDate());
	        }
	    });
		getContentPane().add(adress2Label);
		
		insurenceEndDateField = new JTextField();
		insurenceEndDateField.setBounds(442, 71, 130, 20);
		getContentPane().add(insurenceEndDateField);
		insurenceEndDateField.setColumns(10);
		
		vehicleAddButton = new JButton("Ekle");
		vehicleAddButton.setForeground(Color.BLACK);
		vehicleAddButton.setFont(new Font("Arial", Font.BOLD, 16));
		vehicleAddButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
			    
				
				
			//	driverId=driverIdField.getText();
				licencePlate=licencePlateField.getText();
				insurenceEndDate=insurenceEndDateField.getText();
				lastMaintenance=lastMaintenanceField.getText();
				nextInspection=nextInspectionField.getText();
				km=kmField.getText();
				//int driverId2=Integer.parseInt(driverId);
				int km2=Integer.parseInt(km);
				String insurenceEndDate2= insurenceEndDateField.getText().replaceAll("(\\d+)-(\\d+)-(\\d+)", "$3-$2-$1");
				String lastMaintenance2 = lastMaintenanceField.getText().replaceAll("(\\d+)-(\\d+)-(\\d+)", "$3-$2-$1");
				String nextInspection2 = nextInspectionField.getText().replaceAll("(\\d+)-(\\d+)-(\\d+)", "$3-$2-$1");
				
				
				String insert="INSERT INTO vehicle (vehicle_driver_id,vehicle_licence_plate,vehicle_insurance_enddate,vehicle_last_maintenance," +
			            		"vehicle_km,vehicle_next_inspection,vehicle_availability)";
				String values="VALUES ('"+driverId2+"','"+licencePlate+"','"+insurenceEndDate2+"','"+lastMaintenance2+"','"+km2+"','"+nextInspection2+"','"+vehicleAvailability+"')";
				
				
				
				
				System.out.println("Ready to execute sql");
				 	Connection con = null;
			        Statement st = null;
			        ResultSet rs = null;

			        String url = "jdbc:mysql://localhost:3306/mydb";
			        String user = "root";
			        String password = "qweasdzxc";

			        try {
			            con = (Connection) DriverManager.getConnection(url, user, password);
			            st = (Statement) con.createStatement();
			            st.executeUpdate(insert + values);
			            
			            rs=st.executeQuery("SELECT vehicle_id FROM vehicle WHERE vehicle_licence_plate='"+licencePlate+"'");
			            
			            rs.next();
			            int vId=rs.getInt("vehicle_id");
			            
			            rs=st.executeQuery("SELECT personel_id FROM personel WHERE personel_name='"+selectedDriverName+"'");
			            int personelCounter=0;
			            while(rs.next()){
			            	personelCounter++;
			            }
			            int pId=-1;
			          
			            if(personelCounter>0){
			            	  rs.first();
			            	  pId=rs.getInt("personel_id");
			            }
			            
			            if(driverId2!=-1){
							st.executeUpdate("UPDATE personel set personel_vehicle_id='"+vId+"' WHERE personel_id='"+pId+"'");
							st.executeUpdate("UPDATE vehicle set vehicle_driver_id='"+pId+"'  WHERE vehicle_id='"+vId+"'");
						}
			            
			            
			            int messageType = JOptionPane.PLAIN_MESSAGE;
			          
			            JOptionPane.showMessageDialog(null, "Kayıt Alınmıştır", "Uyarı!!", messageType);
			            con.close();
			        } catch (SQLException ex) {
			            Logger lgr = Logger.getLogger(main.class.getName());
			            lgr.log(Level.SEVERE, ex.getMessage(), ex);

			        } finally {
			            try {
			                if (rs != null) {
			                    rs.close();
			                }
			                if (st != null) {
			                    st.close();
			                }
			                if (con != null) {
			                    con.close();
			                }

			            } catch (SQLException ex) {
			                Logger lgr = Logger.getLogger(main.class.getName());
			                lgr.log(Level.WARNING, ex.getMessage(), ex);
			            }
			        }
			        
			        // this will make sure WindowListener.windowClosing() et al. will be called.
			      //  WindowEvent wev = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
			        //Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(wev);

			        // this will hide and dispose the frame, so that the application quits by
			        // itself if there is nothing else around. 
			        cti.addNewItem();
			        setVisible(false);
			        dispose();
			}});
		
		vehicleAddButton.setBounds(420, 134, 100, 30);
		getContentPane().add(vehicleAddButton);
		
		setVisible(true);  

		
	}
    
    
  
}
